package com.hoolai.qps.codes.netty.logic;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.hoolai.qps.bo.Player;
import com.hoolai.synroom.dispatcher.CmdDispatcher;
import com.hoolai.synroom.dispatcher.SynRoomBusinessCommand;
import com.hoolai.synroom.logic.ExceptionHandler;
import com.hoolai.synroom.logic.SynRoomPlayer;

public class LogicServerChannelHandler extends SimpleChannelUpstreamHandler {

    private static final Logger logger = Logger.getLogger(LogicServerChannelHandler.class);

    private CmdDispatcher cmdDispatcher;

    private ExceptionHandler exceptionHandler;

    public LogicServerChannelHandler(CmdDispatcher cmdDispatcher, ExceptionHandler exceptionHandler) {
        this.cmdDispatcher = cmdDispatcher;
        this.exceptionHandler = exceptionHandler;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        SynRoomPlayer synRoomPlayer = (SynRoomPlayer) ctx.getAttachment();
        if (e.getMessage() instanceof SynRoomBusinessCommand) {
            SynRoomBusinessCommand cmd = (SynRoomBusinessCommand) e.getMessage();
            if (synRoomPlayer == null) {
                logger.error("get synRoomPlayer fail but we an msg, do not process");
                ctx.getChannel().close();
            } else {
                ((Player) synRoomPlayer).setChannelId(cmd.getChannelId());
                cmdDispatcher.dispatch(synRoomPlayer, cmd);
            }
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        if(null == exceptionHandler){
            System.err.println(e.getCause());
        }else{
            exceptionHandler.handleException(e.getCause(), ctx);
        }
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        ctx.setAttachment(new Player(ctx.getChannel().getId(), ctx));
    }

}
